<template>
  <div class="chart"></div>
</template>

<script>
import { merge } from "lodash";
import * as echarts from "echarts"; // 由于echarts版本的更新，此处引入方式对比一年前已经有所区别
import { BAR_BASIC_OPTION } from "./defaultOption";
import ResizeListener from "element-resize-detector";

export default {
  name: "ChartPie",
  props: {
    // 正常的业务数据，对应echarts饼图配置中series[0].data
    seriesData: {
      type: Array,
      required: true,
      default: () => [],
    },
    xAxisData: {
      type: Array,
      required: true,
      default: () => [],
    },
    // 一般UI会规定一个统一的设计规范（比如颜色，字体，图例格式，位置等）
    extraOption: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    seriesData: {
      deep: true,
      handler() {
        this.updateChartView();
      },
    },
  },
  mounted() {
    this.chart = echarts.init(this.$el);
    this.updateChartView();
    window.addEventListener("resize", this.handleWindowResize);
    this.addChartResizeListener();
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleWindowResize);
  },
  methods: {
    /**
     * 将业务数据加入到基础样式配置中
     * @returns {Object} 完整的echart配置
     */
    dataToOption() {
      return merge(
        {},
        BAR_BASIC_OPTION,
        // 这里可以根据UI的设计稿设置颜色
        { color: ["#f75981", "#90e2a9", "#fe883a", "#2d90d1"] },
        {
          xAxis: {
            type: "category",
            data: this.xAxisData,
          },
        },
        {
          series: this.seriesData,
        },
        this.extraOption
      );
    },

    /**
     * 对chart元素尺寸进行监听，当发生变化时同步更新echart视图
     */
    addChartResizeListener() {
      const instance = ResizeListener({
        strategy: "scroll",
        callOnAdd: true,
      });
      instance.listenTo(this.$el, () => {
        if (!this.chart) return;
        this.chart.resize();
      });
    },

    /**
     * 更新echart视图
     */
    updateChartView() {
      if (!this.chart) return;

      const fullOption = this.dataToOption();
      this.chart.setOption(fullOption, true);
    },

    /**
     * 当窗口缩放时，echart动态调整自身大小
     */
    handleWindowResize() {
      if (!this.chart) return;
      this.chart.resize();
    },
  },
};
</script>

<style lang="less" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
